package com.net.xpay.core.manager.impl;

import com.google.common.base.Preconditions;
import com.net.common.annotation.ReadTransactional;
import com.net.common.annotation.WriteTransactional;
import com.net.common.dao.BasicMapper;
import com.net.common.manager.AbstractVersionedManager;
import com.net.noah.core.service.SerialNumberService;
import com.net.xpay.core.dao.PayTransRecordMapper;
import com.net.xpay.core.domain.PayTransRecord;
import com.net.xpay.core.manager.PayTransRecordManager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Component
@ReadTransactional
public class PayTransRecordManagerImpl extends AbstractVersionedManager<PayTransRecord> implements PayTransRecordManager{

    @Autowired
    private PayTransRecordMapper mapper;

    @Autowired
    private SerialNumberService serialNumberService;

    @Override
    @WriteTransactional(propagation = Propagation.SUPPORTS)
    public int save(PayTransRecord obj) {
        Preconditions.checkArgument(obj.getId() == null);
        obj.setId(serialNumberService.getLongSerialNumber(getTableFullName()));
        return super.save(obj);
    }

    @Override
    protected BasicMapper<Long, PayTransRecord> getMapper() {
        return mapper;
    }

    @Override
    public int batchSave(List<PayTransRecord> payTransRecords) {
        if (CollectionUtils.isEmpty(payTransRecords)) {
            return 0;
        }
        for (PayTransRecord record : payTransRecords) {
            record.setId(serialNumberService.getLongSerialNumber(getTableFullName()));
            LocalDateTime now = LocalDateTime.now();
            record.setModifyTime(now);
            record.setCreateTime(now);
            record.setVersion(0L);
        }
        return mapper.batchSave(payTransRecords);
    }

    @Override
    public List<PayTransRecord> listByUserIdAndSummaryId(Long userId, Long summaryId) {
        Preconditions.checkArgument(userId != null && summaryId != null);
        PayTransRecord condition = new PayTransRecord();
        condition.setUserId(userId);
        condition.setSummaryId(summaryId);

        return listByCondition(condition, new ArrayList<>());
    }

    @Override
    public int batchUpdate(List<PayTransRecord> records) {
        if (CollectionUtils.isEmpty(records)) {
            return 0;
        }
        for (PayTransRecord record : records) {
            LocalDateTime now = LocalDateTime.now();
            record.setModifyTime(now);
            record.setVersion(record.getVersion() + 1L);
        }

        return mapper.batchUpdate(records);
    }
}
